<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrderTagsMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Support\ChangeSupport;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportSiteLocationTagData extends Command
{
    /**
     * The name and signature of the console command.
     * @var string
     */
    protected $signature = 'import-site-location-tag-data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '选址中【标签】数据导入';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址');

        if (!$url) {
            $url = 'https://file.51kuafu.com/9e/52/b84a7ccaf993206c70e39344f6dbc0facb0718682f8b29a3e10e79518f3c.csv';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new siteLocationTagData(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class siteLocationTagData implements ToCollection
{

    private string $errMsg = '';

    private array $ratingArr = [];

    public function collection(Collection $collection)
    {
        // 校验列名信息
        $this->checkHeader($collection->first());

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $collection->chunk(100)->map(
            function ($chunk) {
                $chunk->map(
                    function ($item, $row) {
                        $row = $row + 1;

                        if ($row == 1) {
                            return null;
                        }
                        // 常规内容校验
                        list(
                            $shopCode,
                            $shopName,
                            $status,
                            $area,
                            $province,
                            $city,
                            $franchisees,
                            $leasingManager,
                            $BDManager,
                            $signTime,
                            $isRelocate,
                            $isFirst,
                            $tagText,
                            $tagReason,
                            ) = $item;
                        //通过shopCode查询订单号
                        $order    = OpenShopSignOrderModel::query()
                            ->where('shopCode', $shopCode)
                            ->where('status', SignOrderEnum::ORDER_STATUS_OK)
                            ->get()
                            ->first();
                        $tagId    = OpenShopOrderTagsMappingModel::TAG_LIST_SITE_LOCATION_IMPORT_TEXT[$tagText] ?? 0;

                        if ($order && $tagId > 0) {
                            //查询标签信息
                            $tagInfo = OpenShopOrderTagsMappingModel::query()
                                ->where('orderNo', $order->orderNo)
                                ->whereIn(
                                    'tagId', [
                                        OpenShopOrderTagsMappingModel::TAG_TYPE_14, OpenShopOrderTagsMappingModel::TAG_TYPE_15,
                                        OpenShopOrderTagsMappingModel::TAG_TYPE_16, OpenShopOrderTagsMappingModel::TAG_TYPE_17,
                                        OpenShopOrderTagsMappingModel::TAG_TYPE_18,
                                    ]
                                )
                                ->get()
                                ->first();

                            if ($tagInfo) {
                                OpenShopOrderTagsMappingModel::query()
                                    ->where('id', $tagInfo->id)
                                    ->where('tagId', '!=', $tagId)
                                    ->update(['tagId' => $tagId]);
                            } else {
                                OpenShopOrderTagsMappingModel::addTags($order->orderNo, $tagId);
                            }

                            var_dump($order->orderNo, $tagText);
                            // 订单日志
                            $changes = json_encode(
                                [
                                    [
                                        "theme"      => "导入选址中标签",
                                        "changeType" => ChangeSupport::CHANGE_TYPE_SINGLE_INSERT,
                                        "data"       => [
                                            [
                                                "key"         => "text",
                                                "beforeValue" => '',
                                                "afterValue"  => $tagText,
                                                "beforeText"  => '',
                                                "afterText"   => $tagText,
                                                "type"        => ChangeSupport::FILED_TYPE_STRING,
                                                "description" => "选址中标签修改",
                                            ],
                                            [
                                                "key"         => "text",
                                                "beforeValue" => '',
                                                "afterValue"  => $tagReason,
                                                "beforeText"  => '',
                                                "afterText"   => $tagReason,
                                                "type"        => ChangeSupport::FILED_TYPE_STRING,
                                                "description" => "描述说明",
                                            ]
                                        ],
                                    ]
                                ], JSON_UNESCAPED_UNICODE
                            );
                            OpenShopSignOrderLogModel::logInsert(
                                $order->id,
                                OpenShopSignOrderLogModel::SKIP_STEP_UPDATE_SITE_LOCATION_INFO,
                                "系统",
                                0,
                                $changes
                            );
                        }
                    }
                )->filter();
            }
        );
        dump($this->ratingArr);
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "编号",
            "门店名称",
            "状态",
            "区域",
            "省份",
            "城市",
            "加盟商",
            "招商经理",
            "开发经理",
            "签约时间",
            "是否迁址",
            "是否首店选址",
            "客户标签",
            "省区是否继续跟进",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
